<template>
  <div class="mainBackground">
    <div class="rewritePeople">
      <!-- 关闭页面 -->
      <button class="close" @click="close">
        <img src="@/assets/pic2/关闭.png" />
      </button>
      <!-- 导出当前 -->
      <el-button type="primary" @click="download(oldData)">导出</el-button>
      <!-- 导入 -->
      <el-button type="success" @click="upload">导入</el-button>
      <input type="file" accept="text/csv" style="display: none" />
      <!-- 更新 -->
      <el-button type="warning" @click="renew" id="renew">更新</el-button>
      <!-- 表头标题 -->
      <p class="tableTitle">以下表格将展示导入的数据</p>
      <div class="tableDiv">
        <el-table :data="tableData">
          <el-table-column prop="姓名" label="姓名" width="110" />
          <el-table-column prop="出生日期" label="出生日期" width="130" />
          <el-table-column prop="联系电话" label="联系电话" width="130" />
          <el-table-column prop="性别" label="性别" width="90" />
          <!-- <el-table-column prop="出生日期" label="出生日期" width="170" /> -->
          <el-table-column prop="婚姻现状" label="婚姻现状" width="130" />
          <el-table-column prop="人口类型" label="人口类型" width="150" />
          <el-table-column prop="户籍省" label="户籍省" width="150" />
          <el-table-column
            prop="户籍详细地址"
            label="户籍详细地址"
            width="400"
          />
          <el-table-column prop="民族" label="民族" width="100" />
          <el-table-column prop="居住方式" label="居住方式" width="160" />
          <el-table-column prop="居住事由" label="居住事由" width="120" />
          <el-table-column prop="政治面貌" label="政治面貌" width="120" />
          <el-table-column prop="文化程度" label="文化程度" width="170" />
          <el-table-column
            prop="特殊人群类型"
            label="特殊人群类型"
            width="200"
          />
          <el-table-column prop="来本市日期" label="来本市日期" width="130" />
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { getCurrentInstance, onMounted } from "vue";
import pubsub from "pubsub-js";
import axios from "axios";
import { ElMessage } from "element-plus";

import url from "@/components/URL.json";

/* eslint-disable */
export default {
  name: "rewritePeople",
  data() {
    return {
      isNew: false,
      pathInputShow: true,
      pathInput: "",
      tableData: [],
      processShow: false,
      subList: [],
      oldData: [],
      x: "",
      y: "",
    };
  },
  setup() {
    const { proxy } = getCurrentInstance();

    onMounted(() => {
      readFile();
      subscribeList();
    });

    //读取文件
    function readFile() {
      var inputFile = document.querySelector("input[type='file']");
      inputFile.onchange = (event) => {
        // console.log(event);
        var file = inputFile.files[0];

        var fileReader = new FileReader();
        fileReader.readAsText(file, "utf-8");

        fileReader.onload = (event) => {
          var result = fileReader.result;
          // 整理表头
          let header = result.split("\n").shift().split(",");
          // 整理读取的结果s
          let arr = [];
          let dataArr = result.split("\n").slice(1);
          dataArr.forEach((element) => {
            let temp = {};
            let index = 0;
            element.split(",").forEach((e) => {
              let data = e.split("\t")[0].split('"')[1];
              temp[header[index]] = data;
              index++;
            });
            arr.push(temp);
            // console.log(temp);
          });
          proxy.tableData = arr.slice(0, -1);
          proxy.isNew = true;
          ElMessage({
            message: "数据已上传",
            type: "success",
            offset: 50,
            duration: 4000,
          });
        };
      };
    }

    //上传文件
    function upload() {
      document.querySelector("input[type='file']").click();
    }

    // 制作CSV
    function download(data) {
      let str =
        "JZ,XZQ,派出所,姓名,性别,身份证,联系电话,文化程度,出生日期,民族,户口所在地,户籍省,户籍详细地址,婚姻现状,政治面貌,居住方式,居住事由,来本市日期,登记日期,网格,人口类型,地址,location_x,location_y,特殊人群类型\n";

      // 增加\t为了不让表格显示科学计数法或者其他格式
      for (let i = 0; i < data.length; i++) {
        for (const key in data[i]) {
          str += `${data[i][key] + "\t"},`;
          // console.log(str);
        }
        str += "\n";
      }
      // console.log(str)
      // encodeURIComponent解决中文乱码
      const uri =
        "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(str);
      // 通过创建a标签实现
      const link = document.createElement("a");
      link.href = uri;
      // 对下载的文件命名
      link.download = "下载数据.csv";
      link.click();
    }

    // 关闭页面
    function close() {
      pubsub.publish("peopleChangeShow", false);
    }

    // 上传至数据库
    function renew() {
      console.log(proxy.tableData, proxy.x, proxy.y);
      //更替数据
      new Promise((resolve, rej) => {
        // 删除现有
        axios({
          method: "get",
          url: url.basicURL + "deletePeople",
          params: { x: proxy.x, y: proxy.y },
        }).then((res) => {
          if (res.data.flag === 0) {
            ElMessage({
              message: "旧数据已删除",
              type: "success",
              offset: 50,
              duration: 4000,
            });
            resolve();
          } else {
            ElMessage({
              message: "旧数据删除失败",
              type: "error",
              offset: 50,
              duration: 4000,
            });
          }
        });
      }).then(() => {
        // 更新新数据
        axios({
          method: "get",
          url: url.basicURL + "renewPeople",
          params: { data: proxy.tableData },
        }).then((res) => {
          if (res.data.flag === 0) {
            ElMessage({
              message: "新数据已上传",
              type: "success",
              offset: 50,
              duration: 4000,
            });
            setTimeout(() => {
              // 重新载入人口数据
              pubsub.publish("reSearchPeople");
            }, 1000);
          } else {
            ElMessage({
              message: "新数据上传失败",
              type: "error",
              offset: 50,
              duration: 4000,
            });
          }
        });
        // console.log(proxy.tableData);
      });
    }

    //订阅
    function subscribeList() {
      proxy.subList.push(
        pubsub.subscribe("downLoadCSV", (n, data) => {
          proxy.oldData = data.peopleData;
          proxy.x = data.x;
          proxy.y = data.y;
        })
      );
    }

    return { upload, close, download, renew };
  },
  beforeDestroy() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
    this.tableData = [];
  },
};
</script>

<style lang="less" scoped>
#renew {
  margin-left: 12px;
}

.tableTitle {
  font-size: 150%;
  position: relative;
  top: 1.5%;
  left: 1%;
  color: white;
}

.el-button {
  position: relative;
  top: 1%;
  left: 1% !important;
}
.close {
  background-color: transparent;
  width: 40px;
  height: 40px;
  position: absolute;
  z-index: 1000;
  top: 1%;
  right: 1%;
  outline: none;
  border: none;
  border-radius: 50%;
  > img {
    width: 80%;
  }
}
.close:hover {
  cursor: pointer;
}

.mainBackground {
  background-color: rgba(0, 0, 0, 0.5);
  position: absolute;
  top: 0%;
  height: 100%;
  width: 100%;
  z-index: 1001;
}

.rewritePeople {
  border-radius: 15px;
  position: absolute;
  border: 1px solid white;
  background-color: rgba(0, 0, 0, 0.7);
  width: 94%;
  height: 94%;
  top: 3%;
  left: 3%;
  // overflow-y: auto;
  // overflow-x: hidden;
}

.tableDiv {
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;
  top: 2%;
  height: 93%;
  // background-color: #f4ea2a;
}

.tableDiv::-webkit-scrollbar {
  width: 5px;
}

.tableDiv::-webkit-scrollbar-thumb {
  background: #f4ea2a;
  border-radius: 50px;
}

.tableDiv::-webkit-scrollbar-track {
  background: transparent;
}
</style>